import type { Server } from 'socket.io';

const useSocketIoIo = (io: Server) => {
  const dispatchWsServer = io.of('/dispatch');
  const subscribeWsServer = io.of('/subscribe');

  dispatchWsServer.on('connection', (socket) => {
    console.log(socket.id, 'dispatch 客户端连接');
    socket.join('dispatchRoom');

    socket.on('message', (msg) => {
      subscribeWsServer.to('subscribeRoom').emit('message', msg);

      socket.send(`服务器收到的消息是: ${JSON.stringify(msg)}`);
    });

    socket.on('disconnect', () => {
      console.log(`${socket.id} 断开连接`);
    });
  });

  subscribeWsServer.on('connection', (socket) => {
    console.log(socket.id, 'subscribe 客户端连接');
    socket.join('subscribeRoom');
    socket.on('message', (msg) => {
      console.log(`接收到消息: ${msg}`);
      socket.send(`服务器收到的消息是: ${msg}`);
    });
  });

  io.on('connection', () => {
    console.log('连接成功');
  });
};

export default useSocketIoIo;
